// 增强表格组件，可灵活配置
// 1、可根据输入关键字进行模糊筛选
// 2、可配置筛选列
// 3、可配置分页
// 4、暴露新增按钮
// 5、可配置排序
// 6、配置操作列，包含编辑、查看、删除

<template>
  <el-card ref="cardcc" class="table-container">
    <el-row
      style="padding-bottom:10px;"
      :gutter="10"
      type="flex"
      :justify="configs.showFilterRow.show?'space-between':'end'"
    >
      <el-col v-if="configs.showFilterRow.show||false" :span="7">
        <el-input clearable size="small" placeholder="请输入内容" v-model="searchText">
          <el-button type="primary" slot="append" @click="doFilter" icon="el-icon-search"></el-button>
        </el-input>
      </el-col>
      <el-col
        v-if="(configs.operationBtn!=null&&configs.operationBtn.show)||false"
        style="text-align:right;float:right"
        :span="4"
      >
        <el-button
          v-if="configs.operationBtn.add||false"
          size="small"
          type="primary"
          @click="triggerEventAdd"
        >{{configs.operationBtn.addtext||'新增'}}</el-button>
        <el-button
          v-if="configs.operationBtn.output||false"
          size="small"
          type="primary"
          @click="triggerEventOutput"
        >导出</el-button>
      </el-col>
    </el-row>
    <el-row style="padding-bottom:10px;">
      <el-table
        :empty-text="configs.nodata||'暂无数据'"
        :stripe="true"
        class="data-table"
        :border="true"
        :height="tableHeight"
        size="mini"
        :data="showData"
        style="width: 100%"
        fit
        :row-style="{height:'30px'}"
      >
        <!-- <el-table-column type="index" label="#"></el-table-column> -->
        <el-table-column
          v-for="item in configs.columns"
          :key="item.field"
          :prop="item.field"
          :label="item.name"
          :sortable="item.canSort"
          :filters="item.canFilter"
        ></el-table-column>
        <el-table-column
          v-if="(configs.operationCol!=null&&configs.operationCol.show)||false"
          align="center"
          :width="opColWidth"
          label="操作"
        >
          <template slot-scope="scope">
            <el-button
              v-if="configs.operationCol.view||false"
              :type="(configs.operationCol.options!=null&&configs.operationCol.options.view&&configs.operationCol.options.view.type)||'primary'"
              size="mini"
              @click="triggerEventView(scope.$index, scope.row)"
            >{{(configs.operationCol.options!=null&&configs.operationCol.options.view&&configs.operationCol.options.view.text)||'查看'}}</el-button>
            <el-button
              v-if="configs.operationCol.edit||false"
              :type="(configs.operationCol.options!=null&&configs.operationCol.options.edit&&configs.operationCol.options.edit.type)||'warning'"
              size="mini"
              @click="triggerEventEdit(scope.$index, scope.row)"
            >{{(configs.operationCol.options!=null&&configs.operationCol.options.edit&&configs.operationCol.options.edit.text)||'编辑'}}</el-button>
            <el-button
              v-if="configs.operationCol.delete||false"
              size="mini"
              :type="(configs.operationCol.options!=null&&configs.operationCol.options.delete&&configs.operationCol.options.delete.type)||'danger'"
              @click="triggerEventDelete(scope.$index, scope.row)"
            >{{(configs.operationCol.options!=null&&configs.operationCol.options.delete&&configs.operationCol.options.delete.text)||'删除'}}</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-row type="flex" justify="start">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum"
        :page-sizes="[5,10,15,20]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalNum"
      ></el-pagination>
    </el-row>
  </el-card>
</template>

<script>
export default {
  name: "tableX",
  props: {
    tableData: {
      type: Array,
      default() {
        return [];
      }
    },

    configs: {
      type: Object,
      default() {
        return {
          columns: [],
          operationCol: {
            show: true,
            view: false,
            edit: false,
            delete: false,
            download: false,
            options: {
              edit: {},
              delete: {},
              view: {}
            }
          },
          showFilterRow: true,
          operationBtn: {
            show: true,
            add: true,
            output: false
          }
        };
      }
    }
  },
  data() {
    return {
      tableHeight: "200px",
      searchText: "",
      searchword: "",
      queryInfo: {
        pageSize: 5,
        pageNum: 1
      }
    };
  },

  watch: {
    $refs(o, n) {
      let h = this.$refs.cardcc.$el.offsetHeight;
      this.tableHeight = h - 32 - 20 - 52 + "px";
    }
  },
  computed: {
    opColWidth() {
      let opbt = this.configs.operationCol;
      let num = 0;
      if (opbt.view) {
        num++;
      }
      if (opbt.edit) {
        num++;
      }
      if (opbt.delete) {
        num++;
      }
      if (num === 0) {
        return "0px";
      } else if (num === 1) {
        return "80px";
      } else {
        return 20 + 15 * (num - 1) + 56 * num + "px";
      }
    },
    totalNum() {
      return this.filterData.length;
    },
    filterData() {
      this.handleCurrentChange(1);
      let dataresult = this.tableData.filter(item => {
        for (let key in item) {
          if (String(item[key]).search(this.searchword) != -1) {
            return true;
          }
        }
      });
      return dataresult;
    },
    showData() {
      var _this = this;
      return this.filterData.filter((item, index) => {
        return (
          index >= _this.queryInfo.pageSize * (_this.queryInfo.pageNum - 1) &&
          index < _this.queryInfo.pageSize * _this.queryInfo.pageNum
        );
      });
    }
  },
  created() {},

  // updated() {
  //   this.$nextTick(() => {
  //     let h = this.$refs.cardcc.$el.offsetHeight;
  //     this.tableHeight = h - 32 - 20 - 52 + "px";
  //   });
  // },

  mounted() {
    this.$nextTick(() => {
      console.log("this");

      console.log(this);

      let h = this.$refs.cardcc.$el.offsetHeight;
      // this.tableHeight = h - 32 - 20 - 52 + "px";
      if (this.configs.showFilterRow.show || this.configs.operationBtn.show) {
        this.tableHeight = h - 32 - 20 - 52 + "px";
      } else {
        this.tableHeight = h - 32 - 40 + "px";
      }

      let self = this;

      // this.$refs.cardcc.$el.onresize = function() {
      //   let h = self.$refs.cardcc.$el.offsetHeight;
      //   self.tableHeight = h - 32 - 20 - 52 + "px";
      // };

      // this.$refs.cardcc.$el.onload = function() {
      //   let h = self.$refs.cardcc.$el.offsetHeight;
      //   self.tableHeight = h - 32 - 20 - 52 + "px";
      // };

      window.onresize = function() {
        let h = self.$refs.cardcc.$el.offsetHeight;
        // self.tableHeight = h - 32 - 20 - 52 + "px";
        if (self.configs.showFilterRow.show || self.configs.operationBtn.show) {
          self.tableHeight = h - 32 - 20 - 52 + "px";
        } else {
          self.tableHeight = h - 32 - 40 + "px";
        }
      };
    });

    // this.timer = setInterval(() => {
    //   if (
    //     this.$el &&
    //     this.$el.getClientRects &&
    //     this.$el.getClientRects() &&
    //     this.$el.getClientRects()[0]
    //   ) {
    //     let h = this.$el.getClientRects()[0].height;
    //     if (!isNaN(h)) {
    //       clearInterval(this.timer);
    //       if (this.configs.showFilterRow.show) {
    //         this.tableHeight = h - 32 - 20 - 42 + "px";
    //       } else if (!this.configs.operationBtn.show) {
    //         this.tableHeight = h - 32 - 10 + "px";
    //       }
    //     }
    //   }
    // }, 10);
    // // 5秒后还未获取到组件高度，则放弃
    // this.timer2 = setTimeout(() => {
    //   clearInterval(this.timer);
    // }, 5000);
  },
  methods: {
    handleSizeChange(newSize) {
      console.log(newSize);
      this.queryInfo.pageSize = newSize;
    },

    handleCurrentChange(currpage) {
      this.queryInfo.pageNum = currpage;
    },

    //执行模糊筛选
    doFilter() {
      this.searchword = this.searchText;
    },

    triggerEventView(index, row) {
      console.log(row);

      this.$emit("dataView", row);
    },

    triggerEventAdd() {
      this.$emit("dataAdd", {});
    },

    triggerEventOutput() {
      this.$emit("dataOutput", []);
    },

    triggerEventEdit(index, row) {
      this.$emit("dataEdit", row);
    },

    triggerEventDelete(index, row) {
      this.$emit("dataDelete", row);
    },

    triggerEventDownload(index, row) {
      this.$emit("dataDownload", row);
    }
  }
};
</script>

<style lang="less" scoped>
.table-container {
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.15) !important;
  height: 100% !important;

  .space-between {
    display: flex;
    justify-content: space-between;
    flex-flow: row nowrap;
  }
}

/deep/.el-card__body {
  padding: 10px !important;
}

// table {
//   height: calc(~"100% - 94px") !important;
// }
</style>